package com.lyy.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.SQLException;
@Component
public class TransactionManager {

    @Autowired
    private ConnectionUtils connectionUtils;

    public void startTransaction(){
        Connection connection = connectionUtils.getConnection();
        try {
            connection.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("开启事务失败,"+e.toString());
        }
    }

    /**
     * 提交事务
     */
    public void commit(){
        Connection connection = connectionUtils.getConnection();
        try {
            connection.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("提交事务失败,"+e.toString());
        }
    }

    /**
     * 回滚事务
     */
    public void rollBack(){
        Connection connection = connectionUtils.getConnection();
        try {
            System.out.println("业务异常,事务回滚");
            connection.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("回滚事务失败,"+e.toString());
        }
    }
}
